<?php

	include_once("cmsConfig.php");
	
	$authInfo = extractObjectWithKeyFromArray('authInfo', $_SESSION);
	
	if($authInfo->usertype != '0') {
		die("FORBIDDEN");
	}
	
	$formDescriptorTableWriter = new CmsTableWriter( "formdescriptor", $db );
	$formElementTableWriter = new CmsTableWriter("formelement",$db);
	$groupModeTableReader = new CmsTableWriter("grouplist ",$db);
	
	$generateNew = false;
	if( array_key_exists("generateNew",$_REQUEST)) {
		$generateNew = $_REQUEST['generateNew'];
	}
	$formname = extractStringWithKeyFromArray("formname", $_REQUEST);
	$save = extractStringWithKeyFromArray("save", $_REQUEST);
	$formid = extractNumberWithKeyFromArray("formid", $_REQUEST);	
	$formElement = extractArrayWithKeyFromArray("formElement", $_REQUEST);
	
	if ($save =="save changes") {
		
		$formDescriptorTableWriter->begin();
				
		foreach($formDescriptorTableWriter->getTableInfo() as $field ) {		
			$fieldValue = extractNumberWithKeyFromArray( $field["name"], $_REQUEST, 0 );
			
			if($field['name'] == "formname") {
				$formDescriptorTableWriter->addField( $field['name'], $formname );
			} elseif ($field['name'] == "modeaccess") {
				//echo "modeaccess";
				/*
				$Intranet = extractNumberWithKeyFromArray("Intranet", $_REQUEST, 0 );
				$Site = extractNumberWithKeyFromArray("Site", $_REQUEST, 0 );
				$Admin = extractNumberWithKeyFromArray("Admin", $_REQUEST, 0 );
				$Mailout = extractNumberWithKeyFromArray("Mailout",$_REQUEST,0);
				
				$fieldValue = 0;
				if($Intranet == PERMISSION_INTRANET) {
					$fieldValue = $fieldValue + PERMISSION_INTRANET;
				}
				if($Site == PERMISSION_SITE) {
					$fieldValue = $fieldValue + PERMISSION_SITE;
				}
				if($Admin == PERMISSION_ADMIN) {
					$fieldValue = $fieldValue + PERMISSION_ADMIN;
				}
				if($Mailout == PERMISSION_MAILOUT){
					$fieldValue = $fieldValue + PERMISSION_MAILOUT;					
				}
				*/


				$groupModeTableReader->resetCustomIterator("WHERE modemask > 0 ORDER BY modemask");
				while ($g = $groupModeTableReader->nextItem()) {
					$modecode = $g->modecode;
					$$modecode = extractNumberWithKeyFromArray($modecode, $_REQUEST, 0 );
					$fieldValue = $fieldValue + $$modecode;
				}


				$formDescriptorTableWriter->addField( $field['name'], $fieldValue );
			} else {
				$formDescriptorTableWriter->addField( $field['name'], $fieldValue );
			}
			if ( is_array($formElement) && is_numeric($fieldValue) &&  (isset($formElement[$fieldValue]) && is_array($formElement[ $fieldValue ]))){
				
				$actualFormElement = $formElementTableWriter->readItem( $fieldValue );
				$formElementTableWriter->begin();
				foreach( ($formElement[ $fieldValue ]) as $key => $value ) {
					if($value == "on") $value = 1;
					$formElementTableWriter->addField( $key, $value);
				
				}
				$formElementSaved = false;
				if ($actualFormElement) {
					$formElementTableWriter->addField("elementid", $fieldValue);
					$formElementSaved = $formElementTableWriter->saveItem();
				} else {
					//get a pk and save changes.
					//	echo"new";

					$elementId = $formElementTableWriter->db->getId('formelementtablesequence');
					$formElementTableWriter->addField("elementid", $elementId);
					$formElementSaved = $formElementTableWriter->newItem();
				}
			}		
		}
		$formDescriptor = $formDescriptorTableWriter->fields;
		$formid = str_replace("'","", $formDescriptor['formid']);

		$formDescriptorSaved = false;
		if ($generateNew == true) {
			$formDescriptorSaved = $formDescriptorTableWriter->newItem();
		} else {
			$formDescriptorSaved = $formDescriptorTableWriter->saveItem();
		}
		
		if ($formDescriptorSaved){
			$generateNew = false;
		}
		else {
			echo "Not saved";
		}
	} 
?>
<html>
<head>
<title>ContentBox Forminator</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="/cms/css/cms.css" type="text/css">
 <script language="javascript"  src="/cms/html/js/prototype.js" type="text/javascript"></script>
 <script language="javascript" type="text/javascript">
 
 
//bits for the form element editor
	function goAddNewFormElementForKey( key ) {
			var param = 'fieldName=' + key +  '&generateNew=true';
			var opts = { evalScripts: true, method: 'get', parameters: param }
			var ajaxUpdate = new Ajax.Updater('formElementForm_' + key, 'cmsFormElementEditor.php', opts);			
	}
	
	function doFormElementInfoForKey( key ) {
	
		var opt = document.getElementById( key );	
		var val = opt[opt.selectedIndex].value;
		
		var opts = {evalScripts: true, method: 'get', parameters: 'elementId=' + val};
		var ajaxUpdate = new Ajax.Updater('formElementForm_' + key, 'cmsFormElementEditor.php', opts);			
	}

	function doElementSelectForKeyAndValue( key, value ) {
		var opt = document.getElementById( key );
        for (i=0; i < opt.length; i++){
        	if(opt[i].value== value){
        		opt.selectedIndex=i;
        	}
        }
	}
	
	
	function jsInitCheckBoxForKey( key , isChecked) {
		var check = document.getElementById( key );
		check.checked = isChecked;
	}


	function newFormElementAddedForElementIdWithFieldAndLabel(elementId , fieldName, label  ) {
		var opts = document.getElementById( fieldName );
		
		var opt = new Option(label, elementId );
		opt.name = 'newOpt_' + fieldName;

		opts.length = opts.length + 1;
		opts[ opts.length - 1  ]  = opt;
		
        for (i=0; i < opts.length; i++){
	      	if(opts[i].value== elementId ){
        		opts.selectedIndex=i;
        	}
        }
return false;
	}
	

 </script>
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onLoad="javascript:jsInit();">
<div class="formEditorMain">
		<DIV class="angryWarning"> ACHTUNG!! PISSING WITH THIS WILL ONLY END IN HURT</DIV>
<?
	if ($formid == null || !is_numeric($formid) ) {
?>
		<br><br>
		<SPAN class="angryWarning"> hey bozo, there is no valid form specified </SPAN>
<?
	} else {
?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" name="formEditor" id="formEditor" method="post" >
<input type="hidden" name="generateNew" value="<?= $generateNew ?>" />
<?
		{

		
			if ($generateNew == true && $formid == "-1") {
				//we have been asked to generate a new form..
				//so we need to pull an id from the sequence thingeemabob..
				// then create a new object and populate it with sensible values.
				
				//build the initial structure
				foreach($formDescriptorTableWriter->getTableInfo() as $field ){
					$formDescriptor[ $field['name']] = 0;
				}
				// now set some sensible defaults
				$formDescriptor['formname'] = "New Form";
				
				//generate a new id some how.. with the thingee..
				$formDescriptor['formid'] =  $formDescriptorTableWriter->db->getId('formdescriptortablesequence');
//				
//			} else { // we need to suck in the values.. from the form some how?
//			
			} else if ($generateNew == false ) {
				$formDescriptor = $formDescriptorTableWriter->readItem( $formid );
			}

//			echo "<pre>"; print_r($formDescriptor); echo "</pre>";

		
			if ( $formDescriptor  ) {
				foreach ($formDescriptor as $key => $value) {
?>
<div class="formElementBox" >

<div class="formElementLabel"><?= $key ?>:</div>
<div class="formElement">
<?
	switch($key) {
		case "formid"://this is auto magical.. just print it.
			print <<< EOD
			<span id="formid">$value</span><input type="hidden" name="$key" value="$value" />
EOD;
		break;
		case "uid":
		case "gid":
		case "permission":
		case "usertype":
		case "editmode":
		case "formname"://plain old text box for this
			print <<< EOD
			<input name="$key" id="$key" class="formElement" value="$value" />		
EOD;
		break;
		case "modeaccess":
		/*
			$modeaccessArray = array("Admin"=>PERMISSION_ADMIN, "Site"=>PERMISSION_SITE, "Intranet"=>PERMISSION_INTRANET, "Mailout"=>PERMISSION_MAILOUT);
			foreach ($modeaccessArray as $mode=>$modeValue) {
				$isChecked = $modeValue & $value ? "true" : "false";
				print <<< EOD
				<span class="formElementLabel">$mode: </span>
				<input type="checkbox" name="$mode" id="$mode" value="$modeValue" />
EOD;
			$jsCallsForInit[] = "jsInitCheckBoxForKey('$mode', $isChecked)";
			}
		*/

			$modeaccessArray = array();
			$groupModeTableReader->resetCustomIterator("WHERE modemask > 0 ORDER BY modemask");
			while ($g = $groupModeTableReader->nextItem()) {
				$modeaccessArray[$g->groupname] = (int)$g->modemask;
				$groupname = $g->groupname;
				$mode = $g->modecode;
				$modeValue = (int)$g->modemask;
				$isChecked = $modeValue & $value ? "true" : "false";
				print <<< EOD
				<span class="formElementLabel">$groupname: </span>
				<input type="checkbox" name="$mode" id="$mode" value="$modeValue" />
EOD;
																				$jsCallsForInit[] = "jsInitCheckBoxForKey('$mode', $isChecked)";						}

		break;
		//case "websitemodule":
		//case "intranetmodule":
		case "contentmodule":
		case "displaygroup":
		case "sidebarmodule":
		case "activemodule":
			if ($value == "1") 
				$isChecked="true";
			else
				$isChecked ="false";
			print <<< EOD
<input type="checkbox" name="$key" id="$key" value="1" />
EOD;
	$jsCallsForInit[] = "jsInitCheckBoxForKey('$key',$isChecked)";		
		break;

		default: // resort to magic
			//look up the form type, and print its details
			//allow it to be changed? how 
			//put in a dynamic box..
			//that shows the details.. AJAX edit button perhaps.
			//at this point in time..
			//we will only lookup items where the key matches the field 
			//in the form element.

		
			optionList(array("name"=>$key, "id"=>"$key", "class" => "formElement", "onChange"=>"javascript:doFormElementInfoForKey('$key');"), false,null,0,1,"SELECT DISTINCT elementid, label FROM formelement WHERE name = '". $key ."' OR elementid=0", $db);
			print <<< EOD
<a class="formElement" href="javascript:goAddNewFormElementForKey('$key');">Add new form element</a>
EOD;

	$jsCallsForInit[] = "doElementSelectForKeyAndValue('$key', '$value'); doFormElementInfoForKey('$key')";
break;
	}

?>
</div>

<div class="formElementDescription" id="<?= $key ?>Description"><div id="formElementForm_<?= $key ?>"></div></div>
</div>
<?				
				}
			}
		}
?>
<br>
<input type="submit" name="save" value="save changes">
</form>
<br>
<?
	}
?>


</div>
<script language="javascript" type="text/javascript">
		function jsInit() {
<?

	foreach( $jsCallsForInit as $functionToCall) {
		echo $functionToCall .";\n";
	}
?>
	}
</script>
</body>
</html>
<?

//myPrintR($_REQUEST);


?>
